# -*- coding: utf-8 -*- #
"""
Time                2023/08/24 15:41
Author:             mingfeng (SunnyQjm)
Email               mfeng@linux.alibaba.com
File                models.py
Description:
"""
from sqlalchemy import (
    Column,
    BigInteger,
    Integer,
    SmallInteger,
    String,
    Enum,
    JSON,
    DateTime,
    ForeignKey,
    Table,
)
from sqlalchemy.sql import func
from app.database import Base
from sqlalchemy.orm import relationship, backref
from app.schemas import AlertType, AlertStatus, AlertLevel


class BaseModel:
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )


###########################################################################
# Define databse model here
###########################################################################


# class AlertToAlertMerge(Base, BaseModel):
#     __tablename__ = "alert_to_alert_merge"

#     id = Column(Integer, primary_key=True)
#     target_id = Column(Integer, ForeignKey("sys_alert_data.id"))
#     origin_id = Column(Integer, ForeignKey("sys_alert_data.id"))


alert_to_alert_merge = Table(
    "alert_to_alert_merge",
    Base.metadata,
    Column("id", Integer, primary_key=True),
    Column("target_id", Integer, ForeignKey("sys_alert_data.id")),
    Column("origin_id", Integer, ForeignKey("sys_alert_data.id")),
    Column("created_at", DateTime(timezone=True), server_default=func.now()),
)


class AlertData(Base, BaseModel):
    """SAD 格式的告警数据

    Attributes:
        deal_status(str): 处理状态，0-> 未读，1->已读，2 -> 被聚合

        alert_id(str): 告警ID（使用 uuid v4 生成）
        instance(str): 告警实例
        alert_item(str): 告警项，用于唯一标识一类告警，比如每个告警规则可以对应一个告警项
        alert_category(AlertType): 告警类别
        alert_source_type(str): 告警源类型，例如：Grafana、Alert
        alert_time(int): 告警发生时间，采用时间戳，单位为 ms
        status(AlertStatus): 告警状态 normal -> pending -> firing -> resolved
        labels(dict): 告警标签
        annotations(dict): 告警注释
        origin_alert_data: 原始告警数据
    """

    __tablename__ = "sys_alert_data"

    id = Column(Integer, primary_key=True)
    deal_status = Column(SmallInteger, default=0)
    merged_alerts = relationship(
        "AlertData",
        secondary=alert_to_alert_merge,
        primaryjoin=(alert_to_alert_merge.c.target_id == id),
        secondaryjoin=(alert_to_alert_merge.c.origin_id == id),
        backref=backref("merge_targets"),
        # lazy="dynamic",
    )

    alert_id = Column(String(128), unique=True)
    instance = Column(String(254))
    alert_item = Column(String(254))
    alert_category = Column(Enum(AlertType), default=AlertType.OTHER)
    alert_source_type = Column(String(48))
    alert_level = Column(
        Enum(AlertLevel), nullable=False, server_default=AlertLevel.WARNING
    )
    alert_time = Column(BigInteger)
    status = Column(Enum(AlertStatus), default=AlertStatus.NORMAL)
    labels = Column(JSON, default={})
    annotations = Column(JSON, default={})
    origin_alert_data = Column(JSON, default={})
